package leetcode014;

/**
 * https://leetcode.cn/problems/longest-common-prefix/description/
 * 14. 最长公共前缀
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class Study014 {
    public String longestCommonPrefix(String[] strs) {
        String pre = strs[0];
        for (int i = 1; i < strs.length; i++) {
            String cur = strs[i];
            int j = 0;
            for (; j <= cur.length() && j <= pre.length(); j++) {
                if (j == pre.length() || j == cur.length()){
                    break;
                } else if (pre.charAt(j) != cur.charAt(j)) {
                    break;
                }
            }
            pre = pre.substring(0, j);
        }
        return pre;
    }

    public static void main(String[] args) {
        Study014 study014 = new Study014();
        System.out.println(study014.longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(study014.longestCommonPrefix(new String[]{"dog","racecar","car"}));
        System.out.println(study014.longestCommonPrefix(new String[]{"ab","a"}));
        System.out.println(study014.longestCommonPrefix(new String[]{"ab","a", ""}));
    }
}
